<template>
<div class="select-container" :class="{validate: must, error: hasError}">
  <div class="select-wrap">
    <p class="form-control" 
      @click.stop="onChangeDropdown" 
      v-text="selectLabel">
    </p>
    <span class="ico-drop" :class="{actived: isDropdown}"></span>
    <transition name="dropdown">
      <ul class="select-drop" v-show="isDropdown">
        <li v-for="(option, index) in optionsList"
          :key="index" 
          :value="option.value"
          v-text="option.label"
          :class="{selected: option.label === selectLabel}"
          @click.stop="onSelected(option.label, option.value)">
        </li>
      </ul>
    </transition>
    <input type="hidden" ref="select" :name="name" :value="value">
    <input type="text" class="hidden-input" ref="input">
  </div>
  <span class="error-tip" v-show="hasError">请填写此必填项</span>
</div>
</template>

<script>
  export default {
    props: {
      value: [Number, String],
      options: {
        type: Array,
        default() {
          return [
            {value: '1', label: 'wang'}
          ]
        }
      },
      must: {
        type: Boolean,
        default: false
      },
      name: {
        type: String,
        default: null
      },
      // 是否带有“请选择”下拉选项
      defaultSe: {
        type: Boolean,
        default: true
      }
    },
    data() {
      return {
        selectLabel: '请选择',
        isDropdown: false,
        hasError: false
      }
    },
    mounted() {
      this._updateSelected()
    },
    created() {
      if (this.defaultSe) {
        this.options.unshift({value: '', label: '请选择'})
      }
    },
    computed: {
      optionsList() {
        if (this.defaultSe) {
          return this.uniqueArray(this.options)
        }
        return this.options
      }
    },
    methods: {
      /**
       * json数组去重
       */
      uniqueArray(array) {
        var result = [array[0]]
        for (var i = 1; i < array.length; i++) {
          var item = array[i]
          var repeat = false
          for (var j = 0; j < result.length; j++) {
            if (item.value == result[j].value) {
              repeat = true
              break
            }
          }
          if (!repeat) {
            result.push(item)
          }
        }
        return result
      },
      onChangeDropdown(ev) {
        // 默认是成功
        this.hasError = false
        this.isDropdown = !this.isDropdown
      },
      onSelected(label, val) {
        if (!this.must) {
          this.hasError = false
        }
        this.selectLabel = label
        this.isDropdown = false
        this.$emit('input', val)
        this.$emit('on-select', val)
        this.$emit('on-change', { label: label, value: val })
      },
      // 每次更新，和每次初始时调用，设置显示
      _updateSelected() {
        if (!this.must) {
          this.hasError = false
        }
        if (!this.value || this.value === '请选择') {
          this.selectLabel = '请选择'
        } else {
          for (let i in this.options) {
            const option = this.options[i]
            if (this.value == option.value) {
              this.selectLabel = option.label
              break
            }
          }
        }
        document.addEventListener('click', () => {
          if (this.isDropdown) {
            this.isDropdown = false
            // 默认是成功
            this.hasError = true
            if (this.value) {
              // 默认是成功
              this.hasError = false
            }
          }
        }, false)
      },
      // 校验输入项（此处是校验是否选中了）
      _validateInput() {
        // 如果不是必须填写的
        if (!this.must) {
          // 默认是成功
          this.hasError = false
          return false
        }
        // 将失败位置为失败
        this.hasError = !this.value
        return !this.value
      }
    },
    updated() {
      this._updateSelected()
    },
    directives: {
      focus: {
        inserted: function (el, {value}) {
          if (value) {
            el.focus()
          }
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  @import '../scss/_var.scss';
  .select-container {
    display: inline-block;
    position: relative;
    .select-wrap {
      position: relative;
      .form-control {
        min-width: 90px;
        padding-right: 40px;
        border: 1px solid #ddd;
        height: 28px;
        line-height: 28px;
        text-align: left;
        color: #666;
      }
      .ico-drop {
        position: absolute;
        top: 12px;
        right: 10px;
        z-index: 2;
        width: 0;
        height: 0;
        border: 5px solid transparent;
        border-top-color: #444;
        transition: all .2s;
        &.actived {
          transform: rotate(180deg) translateY(8px);
        }
      }
    }
    .select-drop {
      position: absolute;
      width: 100%;
      z-index: 5;
      max-height: 230px;
      padding: 6px 0;
      background: #fff;
      border: 1px solid #d1dbe5;
      border-top-color: transparent;
      overflow-x: hidden;
      li {
        padding: 8px 10px;
        cursor: pointer;
        color: #48576a;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        &.disabled {
          cursor: default;
          background: #eee;
          &:hover {
            color: #48576a;
            background: #eee;
          }
        }
        &.selected {
          color: #fff;
          background: #20a0ff;
          &:hover {
            color: #fff;
            background: #20a0ff;
          }
        }
        &:hover {
          background: #e4e8f1;
        }
      }
    }
    .error-tip {
      position: absolute;
      margin-top: 6px;
      color: $color-error;
      left: 0px;
      white-space: nowrap;
    }
    .hidden-input {
      position: absolute;
      top: 0px;
      z-index: -1;
    }
  }
</style>